package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.QiYe_detail_Adapter;
import com.example.xianji.bean.Collection;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.MyListview;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Main_QiYe_DetailsActivity extends Activity implements OnClickListener {
    private ImageView qiye_details_back;
    private TextView gongsi_detais_title, gongsi_details_place,
            gongsi_details_fuzeren, textview_dianji, textView_phone, gongsi_details_renzheng_state;
    private Boolean click_flag = false;
    private ClipboardManager clipboard;
    private InputMethodManager manager;
    //    private SharedPreferences sp;
//    private Editor ed;
    private int uid;
    private String booth_id;
    private Button button_queding;
    private EditText edittext_details;
    private LinearLayout linearlayout_title;
    private int version_code;
    private MyListview qiye_detail_listview, qiye_detail_product_listview;
    private ArrayList<Collection> detail_list = new ArrayList<Collection>();
    private ArrayList<Collection> product_list = new ArrayList<Collection>();
    private QiYe_detail_Adapter mQiYe_detail_Adapter, mQiYe_detail_Adapter1;
    private ImageView qiye_iamge_collection;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                textview_dianji.setVisibility(View.GONE);
                textView_phone.setVisibility(View.VISIBLE);
            }
            if (msg.what == 2) {
                qiye_detail_listview.setAdapter(mQiYe_detail_Adapter);
                qiye_detail_product_listview.setAdapter(mQiYe_detail_Adapter1);
                qiye_detail_listview.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        Intent intent = new Intent(Main_QiYe_DetailsActivity.this, Main_FuWu_DetailsActivity.class);
                        intent.putExtra("fuwu_details_id", detail_list.get(position).getId());
                        Main_QiYe_DetailsActivity.this.startActivity(intent);
                    }
                });

                qiye_detail_product_listview.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        Intent intent = new Intent(Main_QiYe_DetailsActivity.this, Main_Choose_DaTingActivity.class);
                        intent.putExtra("product_id", product_list.get(position).getId() + "");
                        Main_QiYe_DetailsActivity.this.startActivity(intent);
                    }
                });
            }


        }


    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__qi_ye__details);
        //	XJApplication.getInstance().addActivity(this);

        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_gongsi_details();
            }
        });

        qiye_details_back = (ImageView) findViewById(R.id.qiye_details_back);
        gongsi_detais_title = (TextView) findViewById(R.id.gongsi_detais_title);
        qiye_detail_listview = (MyListview) findViewById(R.id.qiye_detail_listview);

        gongsi_details_place = (TextView) findViewById(R.id.gongsi_details_place);
        qiye_iamge_collection = (ImageView) findViewById(R.id.qiye_iamge_collection);

        gongsi_details_fuzeren = (TextView) findViewById(R.id.gongsi_details_fuzeren);
        textview_dianji = (TextView) findViewById(R.id.textview_dianji);
        textView_phone = (TextView) findViewById(R.id.textView_phone);
        mQiYe_detail_Adapter = new QiYe_detail_Adapter(this, detail_list);
        mQiYe_detail_Adapter1 = new QiYe_detail_Adapter(this, product_list);
        qiye_detail_product_listview = (MyListview) findViewById(R.id.qiye_detail_product_listview);
        gongsi_details_renzheng_state = (TextView) findViewById(R.id.gongsi_details_renzheng_state);
        gongsi_detais_title.setFocusable(true);
        gongsi_detais_title.setFocusableInTouchMode(true);

//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        try {
            version_code = getPackageManager().getPackageInfo(
                    "com.example.xianji", 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        button_queding = (Button) findViewById(R.id.btn_sure_app_version_fragment_home);
        edittext_details = (EditText) findViewById(R.id.edittext_details);
        linearlayout_title = (LinearLayout) findViewById(R.id.linearlayout_title);

        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        hideKeyboard();
        qiye_details_back.setOnClickListener(this);
        textview_dianji.setOnClickListener(this);
        qiye_iamge_collection.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.qiye_details_back) {
            this.finish();
        } else if (v.getId() == R.id.textview_dianji) {
            if (click_flag) {
                click_flag = false;
            } else {
                click_flag = true;
                get_lianxi_phone();
            }
        } else if (v.getId() == R.id.btn_sure_app_version_fragment_home) {
            tijiao_neirong();
        } else if (v.getId() == R.id.qiye_iamge_collection) {
            if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
                collection();
            } else {
                Contant.come_from_fuwuDetail = 1;
                startActivity(new Intent(Main_QiYe_DetailsActivity.this, Main_LoginActivity.class));
            }
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void get_gongsi_details() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("version", version_code + "");
        map.put("booth_id", getIntent().getIntExtra("gongsi_id", 0) + "");
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.gongsi_detais,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");
                        JSONObject object1 = array.getJSONObject(0);
                        JSONArray array2 = array.getJSONArray(1);
                        Log.i("zzzzzz", array2 + "");
                        JSONArray array3 = array.getJSONArray(2);
                        gongsi_detais_title.setText(object1.getString("title"));
                        gongsi_details_place.setText(object1.getJSONObject("uinfo").getString("address"));
                        if (object1.getJSONArray("boothcate").length() > 0) {
                            JSONObject obj = object1.getJSONArray("boothcate").getJSONObject(0);
                            booth_id = obj.getString("booth_id");
                        }
                        if (object1.getJSONObject("usrs").getString("authen").equals("D")) {
                            gongsi_details_renzheng_state.setText("未认证");
                        } else if (object1.getJSONObject("usrs").getString("authen").equals("A")) {
                            gongsi_details_renzheng_state.setText("申请中");
                        } else if (object1.getJSONObject("usrs").getString("authen").equals("N")) {
                            gongsi_details_renzheng_state.setText("未认证");
                        } else if (object1.getJSONObject("usrs").getString("authen").equals("Y")) {
                            gongsi_details_renzheng_state.setText("认证通过");
                        }

                        gongsi_details_fuzeren.setText(object1.getJSONObject("uinfo").getString("name"));
                        uid = object1.getJSONObject("uinfo").getInt("uid");
                        textView_phone.setText(object1.getJSONObject("usrs").getString("mobile"));
                        if (object1.getJSONObject("uinfo").getInt("isopen") == 0) {
                            textview_dianji.setVisibility(View.GONE);
                            textView_phone.setText(object1.getJSONObject("usrs").getString("mobile"));
                            textView_phone.setVisibility(View.VISIBLE);
                        } else {
                            textview_dianji.setVisibility(View.GONE);
                            textView_phone.setVisibility(View.VISIBLE);
                        }
                        for (int i = 0; i < array2.length(); i++) {
                            JSONObject obj = array2.getJSONObject(i);
                            Collection mCollection = new Collection();
                            mCollection.setTitle(obj.getString("title"));
                            mCollection.setDetail(obj.getString("details"));
                            mCollection.setId(obj.getInt("id"));
                            detail_list.add(mCollection);
                        }
                        for (int i = 0; i < array3.length(); i++) {
                            JSONObject obj = array3.getJSONObject(i);
                            Collection mCollection = new Collection();
                            mCollection.setTitle(obj.getString("title"));
                            mCollection.setDetail(obj.getString("details"));
                            mCollection.setId(obj.getInt("id"));
                            product_list.add(mCollection);
                        }
                    }
                    handler.sendEmptyMessage(2);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

					/*if(mCustomProgressDialog!=null){
						mCustomProgressDialog.dismiss();
						
						mCustomProgressDialog=null;
					}*/
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    public void get_lianxi_phone() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("uid", uid);
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.huoqu_phone,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_QiYe_DetailsActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(2);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 确定提交内容
     */
    public void tijiao_neirong() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("booth_id", getIntent().getIntExtra("gongsi_id", 0) + "");
        map.put("details", edittext_details.getText().toString());
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.fuwu_liuyan,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_QiYe_DetailsActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        Main_QiYe_DetailsActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    //收藏
    public void collection() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("id", getIntent().getIntExtra("gongsi_id", 0) + "");
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        parms.addBodyParameter("title", gongsi_detais_title.getText().toString());
        parms.addBodyParameter("type", "service");//type = service  是企业
        httpUtils.send(HttpMethod.POST, Contant.collection, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject object = new JSONObject(arg0.result);
                    Toast.makeText(Main_QiYe_DetailsActivity.this, object.getString("msg"), Toast.LENGTH_SHORT).show();

                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
